import React from 'react'
import {connect} from 'react-redux'
import { Button, Tabs, Popover, Modal, message, Col, Select, Spin, Row } from 'antd'
const TabPane = Tabs.TabPane;
import httpFetch from 'share/httpFetch'
import config from 'config'
import 'styles/financial-management/finance-audit/audit.scss'
import CustomTable from 'components/custom-table'
import SearchArea from 'components/search-area'
import menuRoute from 'routes/menuRoute'
import { messages, invoiceAmountChange, dealCache, deepFullCopy, queryCurrencyPrecision,
  dealListTag } from "share/common";
import financeAuditService from 'containers/financial-management/finance-audit/finance-audit.service'
import CostCenterSearchForm from 'components/template/cost-center-search-form/cost-center-search-form'
import configureStore from "stores";
import {setFinanceAudit, setFinanceAuditParams} from "actions/cache";
import ReconnectingWebSocket from "reconnectingwebsocket";
const Option = Select.Option;
let cacheSearchData={};
let defaultSearchForm=[];
import DepartmentPicker from 'containers/financial-management/wait-for-billing/new-billing/department-picker';
import debounce from "lodash.debounce";
import Condition from 'components/condition'
const { If } = Condition;

class FinanceAudit extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      page: 0,
      pageSize: 10,
      data: [],
      hasConfirm: false,
      pagination: {
        total: 0,
        showQuickJumper: true,
        showSizeChanger: true,
        onShowSizeChange: this.onChangePagerSize,
        pageSizeOptions: ['10','20','50','100','200']
      },
      invoiceColumns: [
        {title: messages('financial-management.key166'/*序号*/), dataIndex: "index", width: 72, fixed: 'left'},
        {title: messages('financial-management.key131'/*申请人*/), dataIndex: "applicantName"},
        {title: messages('financial-management.key130'/*工号*/), dataIndex: "employeeID", width: 100},
        {title: messages('financial-management.key132'/*提交日期*/), dataIndex: "submittedDate", width: 120, render: date => new Date(date).format('yyyy-MM-dd'), sorter: true},
        {
          title: messages('financial-management.key133'/*单据类型*/), dataIndex: 'formName', width: 200, render: formName => (
          <Popover content={formName}>
            {formName}
          </Popover>
        ),sorter: true},
        {title: messages('financial-management.key167'/*报销单号*/) , dataIndex: 'childBusinessCode', width: 200, render: (text, record, index) => {
          let showText = !record.parentBusinessCode && record.businessCode ||
            record.parentBusinessCode !== record.childBusinessCode && (record.parentBusinessCode + '-' + record.childBusinessCode) ||
            record.childBusinessCode;
          return (
            <Popover content={showText}>
              {showText}
            </Popover>
          )
        }, sorter: true},
        {title: messages('financial-management.key660')/*发票袋编号*/, dataIndex: 'expBagCode', width: 1},
        {title: messages('financial-management.key135'/*币种*/), dataIndex: "currencyCode", width: 72},
        {
          title: messages('financial-management.key136'/*总金额*/), dataIndex: "totalAmount", width: 150,align: "right",
          render: (totalAmount, record) => {
            let showText = invoiceAmountChange(record.reviewedFlag, totalAmount, record.currencyCode);
            return (<Popover content={showText}>
              {showText}
            </Popover>)
          },
          sorter: true},
        {title: messages('financial-management.key168'/*支付币种*/), dataIndex: "baseCurrency", width: 100},
        {title: messages('financial-management.key169'/*待支付金额*/), dataIndex: "baseCurrencyRealPaymentAmount", width: 150,align: "right", render:(value,record) => this.duePay(value,record.baseCurrency), sorter: true},
        {
          title: messages('financial-management.key170'/*凭证编号*/),
          dataIndex: "origDocumentSequence",
          width: 1,
          render: value => {
            return <Popover content={value} placement="topLeft">{value}</Popover>
          }
        }
      ],
      borrowColumns: [
        {title: messages('financial-management.key166'/*序号*/), dataIndex: "index", width: 72},
        {title: messages('financial-management.key130'/*工号*/), dataIndex: "employeeID", width: 120},
        {title: messages('financial-management.key131'/*申请人*/), dataIndex: "applicantName"},
        {title: messages('financial-management.key132'/*提交日期*/), dataIndex: "submittedDate", width: 150, render: date => new Date(date).format('yyyy-MM-dd')},
        {
          title: messages('financial-management.key133'/*单据类型*/), dataIndex: 'formName', width: 250, render: formName => (
          <Popover content={formName}>
            {formName}
          </Popover>
        )
        },
        {title: messages('financial-management.key171'/*申请单号*/), dataIndex: 'businessCode', width: 250},
        {title: messages('financial-management.key135'/*币种*/), dataIndex: "currencyCode", width: 72, render: text => text || this.props.companyConfiguration.currencyCode},
        {title: messages('financial-management.key169'/*待支付金额*/), dataIndex: "paymentAmount", width: 120, align: "right",render: (value,record) => this.duePay(value,record.currencyCode)},
        {
          title: messages('financial-management.key170'/*凭证编号*/),
          dataIndex: "origDocumentSequence",
          width: 1,
          render: value => {
            return <Popover content={value} placement="topLeft">{value}</Popover>
          }
        }
      ],
      nowType: 'INVOICE',
      status: 'prending_audit',   //当前状态
      tabs: [
        {key: 'prending_audit', name: messages('financial-management.key191'/*待审核*/)},
        {key: 'audit_pass', name: messages('financial-management.key192'/*已审核*/)}],
      searchParams: {},
      searchForm: [
        {
          type: 'radio',
          id: 'type',
          label: messages('financial-management.key133'/*单据类型*/),
          options: [
            {label: messages('financial-management.key160'/*报销单*/), value: 'INVOICE'},
            {label: messages('financial-management.key161'/*借款单*/), value: 'BORROW'}],
          event: 'CHANGE_TYPE',
          defaultValue: 'INVOICE'
        },
        // {
        //   type: 'select',
        //   id: 'auditStatus',
        //   label: messages('expense-11.key25'/*审核状态*/),
        //   options: [
        //     {label: messages('financial-management.key1245'/*预审中*/), value: 'audit_review'},
        //     {label: messages('financial-management.key1246'/*复审中*/), value: 'audit_review_passed'}],
        // },
        // {
        //   type: 'select',
        //   id: 'receiveStatus',
        //   label: messages('financial-management.key1247'/*收件状态*/),
        //   options: [
        //     {label: messages('financial-management.key1248'/*未收件*/), value: 0},
        //     {label: messages('financial-management.key1249'/*已收件*/), value: 1},
        //     {label: messages('financial-management.key1250'/*无需收件*/), value: 3}],
        // },
        {
          type: 'searcher',
          id: 'formOIDs',
          label: messages('financial-management.key176'/*表单类型*/),
          listType: 'authority_form',
          descriptionKey: 'companyName',
          labelKey: 'formName',
          valueKey: 'formOID',
          listExtraParams: {formType: 1002}
        },
        {
          type: 'items',
          id: 'dateRange',
          items: [
            {type: 'date', id: 'dateFrom', label: messages('financial-management.key126'/*提交日期从*/)}, //提交日期从
            {type: 'date', id: 'dateTo', label: messages('financial-management.key127'/*提交日期至*/)} //提交日期至
          ]
        },
        {
          type: 'items',
          id: 'approvalDateRange',
          items: [
            {type: 'date', id: 'approvalStartDate', label: messages('financial-management.key193'/*审批日期从*/)},
            {type: 'date', id: 'approvalEndDate', label: messages('financial-management.key194'/*审批日期至*/)}
          ]
        },
        {
          type: 'combobox', id: 'formID', label: messages('financial-management.key134'/*单号*/),
          placeholder: messages('common.please.enter') + messages('financial-management.key134'/*单号*/),
          options: [],
          searchUrl: `${config.baseUrl}/api/expense/report/search`,
          method: 'get',
          searchKey: 'keyword', getParams: {status: 'prending_audit'}, labelKey: '_self', valueKey: '_self'
        },
        {
          type: 'combobox',
          id: 'user',
          label: messages('financial-management.key164'/*员工*/),
          placeholder: messages('common.please.enter') + messages('financial-management.key123'/*申请人姓名/工号*/),
          options: [],
          searchUrl: `${config.baseUrl}/api/users/v3/search?page=0&size=9999&roleType=TENANT&status=all`,
          method: 'get',
          searchKey: 'keyword',
          labelKey: 'fullName',
          valueKey: 'userOID',
          renderOption: option => (`${option.eid}-${option.employeeID}-${option.fullName}${(option.status !== 1001 ? (
            `（${option.status === 1002 ? messages('financial-management.key622')/*待离职员工*/ : messages('financial-management.key623')/*离职员工*/}）`
          ) : '')}`)
        },
        {
          type: 'multiple',
          id: 'legalEntity',
          label: messages('financial-management.key128'/*法人实体*/),
          options: [],
          getUrl: `${config.baseUrl}/api/v2/my/company/receipted/invoices?page=0&size=100`,
          method: 'get',
          labelKey: 'companyName',
          valueKey: 'companyReceiptedOID'
        },
        {
          type: 'items', id: 'priceRange', items: [
            {type: 'inputNumber', id: 'minTotalAmount', label: messages('financial-management.key196'/*金额从*/)},
            {type: 'inputNumber', id: 'maxTotalAmount', label: messages('financial-management.key197'/*金额至*/)}
          ]
        },
        {
          type: 'items', id: 'honestRange', items: [
            {type: 'inputNumber', id: 'creditScoreFrom', label: messages('financial-management.key813')/*信用分从*/, precision: 1, step: 0.1, min: -9999},
            {type: 'inputNumber', id: 'creditScoreTo', label: messages('financial-management.key814')/*信用分到*/, precision: 1, step: 0.1, min: -9999}
          ]
        },
        // {
        //   type: 'select',
        //   id: 'creditRank',
        //   label: '信用等级',
        //   options: [],
        //   getUrl: `${config.baseUrl}/api/v2/my/company/receipted/invoices?page=0&size=100`,
        //   method: 'get',
        //   labelKey: 'companyName',
        //   valueKey: 'companyReceiptedOID'
        // }
      ],
      printFreeForm: {
        type: 'select',
        id: 'printFree',
        label: messages('financial-management.key198'/*是否免打印*/),
        options: [
          {label: messages('financial-management.key199'/*全部*/), value: 'null'},
          {label: messages('financial-management.key200'/*免打印*/), value: 'true'},
          {label: messages('financial-management.key201'/*非免打印*/), value: 'false'}]
      },
      labelForm: {
        type: 'multiple',
        id: 'labelIds',
        label: messages('financial-management.key574')/*单据标签*/,
        options: [],
        getUrl: `${config.baseUrl}/api/expense/labels?labelCategory=1`,
        method: 'get',
        labelKey: 'name',
        valueKey: 'id'
      },
      expenseDetailAudit: menuRoute.getRouteItem('expense-report-detail-audit'),
      loanDetailAudit: menuRoute.getRouteItem('loan-detail-audit'),
      scanAudit: menuRoute.getRouteItem('scan-audit'),
      scanGunAudit: menuRoute.getRouteItem('scan-gun-audit'),
      sort: '',
      isPrintFreeSearch:false,
      optionLoading: false,
      expOption: [],
      departmentOids: [],
      auditStatus: undefined,
      receiveStatus: undefined,
      billed: undefined
    };
    this.handleEnterInvoiceCode = debounce(this.handleEnterInvoiceCode, 250);
    this.connector = null;
    this.data = [];
  }
  componentWillMount() {
    if(this.connector)
      this.connector.close();
    !window.ISIE9 && this.openWebSocket();
    let params = [
      {factorCode:"COMPANY",factorValue: this.props.user.companyId},
      {factorCode:"SET_OF_BOOKS",factorValue: this.props.company.setOfBooksId}
    ];
    httpFetch.post(`${config.baseUrl}/config/api/config/hit/EXPENSE_REPORT_PRINT_FREE?tenantId=${this.props.user.tenantId}`, params).then( res => {
      const { searchForm, labelForm, printFreeForm } = this.state;
      searchForm.filter(item => item.id === 'labelIds').length === 0 && searchForm.push(labelForm);
      defaultSearchForm.push(JSON.parse(JSON.stringify(labelForm)));
      if (res.data.rows[0].hitValue === 'Y') {
        defaultSearchForm.push(JSON.parse(JSON.stringify(printFreeForm)));
        this.state.printFreeForm.defaultValue = cacheSearchData['printFree'];
        searchForm.push(printFreeForm);
      }
      this.setState({searchForm, isPrintFreeSearch: res.data.rows[0].hitValue === 'Y'});
    });
    this.setState({
      status: this.props.params.tab !== ':tab' ? this.props.params.tab : 'prending_audit'
    }, () => {
      // this.formRef.setValues(this.props.financeAuditParams);
      if (localStorage.getItem('isBackFinance') !== 'true') {
        configureStore.store.dispatch(setFinanceAuditParams(null));
      } else {
        localStorage.setItem('isBackFinance', false)
      }
      this.getCache();
    })
  }
  componentWillUnmount = () => {
    if(this.connector)
      this.connector.close();
  };

  //webSocket读图审核开始
  openWebSocket = () => {
    let url = `${config.wsUrl}/ws/scancode?scanMode=REVIEW`;
    this.connector = new ReconnectingWebSocket(url);
    this.connector.onopen = this.onOpen;
    this.connector.onerror = this.onError;
    this.connector.onmessage = this.onMessage;
    this.connector.onclose = this.onClose;
  };

  onOpen = () => {
    let body = {
      userOID: this.props.user.userOID,
      token: this.props.authToken.access_token
    };
    let dict = {
      command: 'AUTH',
      body: JSON.stringify(body)
    };
    let dataSend = JSON.stringify(dict) + '\0';
    this.connector.send(dataSend);
  };

  onError = (error) => {
    this.setState({connectStatus: false})
  };

  onMessage = (message) => {
    this.data.push(JSON.parse(JSON.stringify(message)).data);
    this.analyseData();
  };

  onClose = () => {
    if (this.state.connectStatus)
      this.setState({connectStatus: false});
  };

  analyseData = () => {
    let lastReceive = this.data.pop();
    let end = '\0';
    if (lastReceive.indexOf(end) === -1) {
      this.data.push(lastReceive);
      return;
    }
    let temp = lastReceive.split(end);
    let expense = JSON.parse(this.data.join('') + temp[0]);
    if (temp[1] !== '') {
      this.data = [];
      this.data.push(temp[1]);
    }
    if (expense.command === 'ERROR') {
      if (this.state.hasConfirm)
        return;
      this.setState({hasConfirm: true});
      Modal.confirm({
        title: 'Oops',
        content: expense.body,
        okText: messages('financial-management.key202'/*重连*/),
        cancelText: messages('common.cancel')/*取消*/,
        onOk: () => {
          this.setState({hasConfirm: false});
        },
        onCancel: () => {
          this.setState({hasConfirm: false});
          this.data = [];
          this.connector.close();
        }
      });
      return;
    }

    expense.body = JSON.parse(expense.body);

    if (!expense.body || !expense.body.type || !expense.body.content) return;
    if (expense.command !== 'MESSAGE') return;
    let content = expense.body.content.split(':');
    if ('AUTH_SUCCESS' === expense.body.type) {
      this.setState({connectStatus: true});
    } else if ('BILL_REVIEW' === expense.body.type) {
      let { expenseDetailAudit, loanDetailAudit } = this.state;
      let url = '';
      Number(content[0]) === 1002 && (url = expenseDetailAudit.url.replace(':expenseReportOID', content[2]).replace(':backType', 'history').replace(':tab','prending_audit'));
      Number(content[0]) === 3001 && (url = loanDetailAudit.url.replace(':formOID', content[1]).replace(':loanBillOID', content[2]).replace(':backType', 'history').replace(':tab','prending_audit'));
      configureStore.store.dispatch(setFinanceAudit(cacheSearchData));
      this.context.router.push(url);
    }
  };
  //webSocket读图审核结束

  duePay = (value,currencyCode) => {
    let text = this.filterMoney(value,queryCurrencyPrecision(currencyCode));
    return (<Popover content={text}>{text}</Popover>)
  };

  getList = () => {
    this.setState({loading: true});
    const { pagination, searchParams, status } = this.state;
    let temp = deepFullCopy(searchParams);
    temp.status = status;
    if(pagination.total !== 0){
      temp.total = pagination.total;
    }
    httpFetch.post(`${config.baseUrl}/api/${this.state.nowType === 'INVOICE' ? 'v2/expense/reports/finance/admin/search' : 'loanBill/finance/query/by/page'}?page=${this.state.page}&size=${this.state.pageSize}&sort=${this.state.sort}`, temp).then(res => {
      let data = res.data.map((item, index) => {
        item.index = this.state.page * this.state.pageSize + index + 1;
        return item;
      });
      let arr = [];
        data && data.map(item => {
          if (item.warningList) {
            let list = JSON.parse(item.warningList);
            if (list && list.length === 1 && list[0].externalPropertyName === 'CREDIT_SPOT_CHECK') {
              item.warningList = undefined;
            }
            if (list && list.length > 1) {
              let arr = [];
              list.map(item => {
                if (item.externalPropertyName !== 'CREDIT_SPOT_CHECK') {
                  arr.push(item)
                }
              })
              item.warningList = JSON.stringify(arr);
            }
          }
        })
      pagination.total = Number(res.headers['x-total-count']);
      pagination.current = this.state.page + 1;
      this.setState({
        loading: false,
        page:0,
        data,
        pagination
      });
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({loading: false});
    })
  };

  onChangePagerSize = (current, size) => {
    if(size !== this.state.pageSize)
      this.setState({
        page: 0,
        pageSize: size
      })
  };

  handleClickSwitch = () => {
    this.context.router.push(this.state.scanAudit.url)
  };

  handleClickSwitchGun = () => {
    this.context.router.push(this.state.scanGunAudit.url)
  };

  //渲染Tab头
  renderTabs() {
    return (
      this.state.tabs.map(tab => {
        // let typeCount = this.state.count[tab.key];
        return <TabPane tab={`${tab.name}`}
                        key={tab.key}/>
      })
    )
  }

  //渲染处理数据源
  handleData = () => {
    let {invoiceColumns, borrowColumns, status, isPrintFreeSearch, nowType, printFreeForm, labelForm, searchForm} = this.state;
    let search = deepFullCopy(searchForm);
    search.map((item, index) => {
      item.type === 'items' && (item.items = searchForm[index].items);
    });
    search.map((item) => {
        if(item.id === 'formID'){
          let url = config.baseUrl;
          if (nowType === 'INVOICE') {
            url += `/api/expense/report/search`;
          } else {
            url += `/api/loanBill/query/business/code/by/keyword`
          }
          item.searchUrl = url;
          item.getParams = {status};
        }
      if(item.id === 'formOIDs'){
        let temp = {};
        if (nowType === 'INVOICE') {
          temp.formType = 1002;
        } else {
          temp.formType = 3001;
        }
        item.listExtraParams = temp;
      }
    });
    let indexLabel = search.indexOf(search.filter(item => item.id === 'labelIds')[0]);
    let indexPrint = search.indexOf(search.filter(item => item.id === 'printFree')[0]);
    if(indexLabel > -1){
      indexPrint > -1 ? search.splice(indexLabel,2) : search.splice(indexLabel,1);
    }
    if(nowType === 'INVOICE')
    {
      search.filter(item => item.id === 'labelIds').length === 0 && search.push(labelForm);
      isPrintFreeSearch && search.push(printFreeForm);
    }
    this.setState({ invoiceColumns, borrowColumns, searchForm: search});
  };
  //Tab点击事件
  onChangeTabs = (key) => {
    this.setState({
      loading: true,
      page: 0,
      status: key
    }, () => {
      this.handleData();
      this.child.handleSearch();
    });
  };

  search = (result) => {
    const { searchParams, departmentOids } = this.state;
    searchParams.searchCostCenterCommands && (result.searchCostCenterCommands = searchParams.searchCostCenterCommands);
    typeof searchParams.isRefBagCode === 'boolean' && (result.isRefBagCode = searchParams.isRefBagCode);
    searchParams.expBagCode && (result.expBagCode = searchParams.expBagCode);
    result.departmentOids = departmentOids;
    this.setCache(result);
    result.dateFromTrans = result.dateFrom ? result.dateFrom.format('YYYY-MM-DD 00:00:00') : undefined;
    result.dateToTrans = result.dateTo ? result.dateTo.format('YYYY-MM-DD 23:59:59') : undefined;
    result.approvalStartDateTrans = result.approvalStartDate ? result.approvalStartDate.format('YYYY-MM-DD 00:00:00') : undefined;
    result.approvalEndDateTrans = result.approvalEndDate ? result.approvalEndDate.format('YYYY-MM-DD 23:59:59') : undefined;
    let oids = [];
    departmentOids.map(item => {
      oids.push(item.value);
    });

    if(result.creditScoreFrom > result.creditScoreTo){
      message.error(messages('financial-management.key815')/*信用分应从低到高*/);
      return -1;
    }
    if(result.minTotalAmount > result.maxTotalAmount){
      message.error(messages('financial-management.key609')/*金额上限应大于金额下限*/);
    }else{
      let searchParams = {
        applicantOID: result.user,
        businessCode: result.formID,
        corporationOIDs: result.legalEntity,
        endDate: result.dateToTrans,
        startDate: result.dateFromTrans,
        formOIDs: result.formOIDs,
        approvalStartDate: result.approvalStartDateTrans,
        approvalEndDate: result.approvalEndDateTrans,
        printFree: result.printFree,
        departmentOids: oids,
        minTotalAmount: result.minTotalAmount,
        maxTotalAmount: result.maxTotalAmount,
        labelIds: result.labelIds,
        searchCostCenterCommands: result.searchCostCenterCommands,
        isRefBagCode: result.isRefBagCode,
        expBagCode: result.expBagCode,
        creditScoreFrom: result.creditScoreFrom,
        creditScoreTo: result.creditScoreTo,
        auditStatus: this.state.auditStatus || (this.props.financeAuditParams && this.props.financeAuditParams.auditStatus),
        receiveStatus: this.state.receiveStatus || (this.props.financeAuditParams && this.props.financeAuditParams.receiveStatus),
        billed: this.state.billed || (this.props.financeAuditParams && this.props.financeAuditParams.billed)
      };
      configureStore.store.dispatch(setFinanceAuditParams(searchParams));
      this.setState({
        searchParams,
        loading: true,
        page: result.page?result.page:0
      }, () => {
        this.getList();
      })
    }
  };

  //子组件this
  onRef = (ref) =>{
    this.child=ref;
  }
  //存储筛选数据缓存
  setCache(result){
    let {status,page} = this.state;
    result.tabsStatus = status;
    result.page = page;
    cacheSearchData=result;
  }

  //获取筛选数据缓存
  getCache(){
    let result = this.props.financeAudit;
    if(result&&JSON.stringify(result) !== "{}"){
      cacheSearchData=result;
      // 很傻逼的问题，没搞懂为啥搜索后点进详情后再返回列表的搜索下拉框没有数据了，先这么改吧
      result.auditStatusOption = [
        {label: messages('financial-management.key1245'/*预审中*/), value: 'audit_review'},
        {label: messages('financial-management.key1246'/*复审中*/), value: 'audit_review_passed'}
      ]
      this.dealCache(deepFullCopy(result));
    }
    else{
      defaultSearchForm=deepFullCopy(this.state.searchForm);
      this.getList();
    }
  };

  //处理筛选缓存数据
  dealCache(result) {
    let {status, searchForm, nowType, page, departmentOids} = this.state;
    defaultSearchForm=deepFullCopy(searchForm);
    if (result) {
      status = result.tabsStatus;
      nowType = result.type;
      page = result.page;
      departmentOids = result.departmentOids;
      dealCache(searchForm, deepFullCopy(result));
      this.setState({status, nowType, searchForm, page, departmentOids}, () => {
        this.handleData();
        this.search(deepFullCopy(result));
        configureStore.store.dispatch(setFinanceAudit(null));
      })
    }
  }

  clear = () => {
    cacheSearchData={};
    this.setState({
      page:0,
      searchForm:defaultSearchForm,
      nowType: 'INVOICE',
      departmentOids: [],
      searchParams: {}
    },()=>{
      this.handleData();
      this.getList();
    });
  };

  searchEventHandle = (event, value, valuesTmp) => {
    switch (event) {
      case 'CHANGE_TYPE': {
        if (value === this.state.nowType)
          return;
        this.setState({page: 0, nowType: value, loading: true}, () => {
          this.formRef.setValues({
            formOIDs: undefined
          });
          valuesTmp.formOIDs = undefined;
          valuesTmp.formOIDsLable = undefined;
          valuesTmp.type = value;
          valuesTmp.typeLable = value;
          this.handleData();
          this.search(valuesTmp);
        });
        break;
      }
    }
  };

  handleTableChange = (pagination, filters, sorter) => {
    let page =  pagination.current;
    let sort = '';
    if(sorter.order){
      sort = `${sorter.columnKey},${sorter.order === 'ascend' ? 'ASC' : 'DESC'}`
    }
    this.setState({
      page: page - 1,
      loading: true,
      sort
    }, ()=>{
      this.child.handleSearch();
    })
  };

  handleRowClick = (record) => {
    const { nowType, status, expenseDetailAudit, loanDetailAudit } = this.state;
    let url = '';
    if(nowType === 'INVOICE')
      url = expenseDetailAudit.url.replace(':expenseReportOID', record.expenseReportOID).replace(':backType','history');
    else
      url = loanDetailAudit.url.replace(':formOID', record.formOID).replace(':loanBillOID', record.loanBillOid).replace(':backType','history');
    status === 'prending_audit' && (url = url.replace(':tab','prending_audit'));
    status === 'audit_pass' && (url = url.replace(':tab','audit_pass'));
    configureStore.store.dispatch(setFinanceAudit(cacheSearchData));
    this.context.router.push(url);
  };

  changeCostCenter = (value) => {
    const { searchParams } = this.state;
    searchParams.searchCostCenterCommands = value;
    this.setState({searchParams})
  };

  handleEnterInvoiceCode = value => {
    const { status, searchParams } = this.state;
    searchParams.expBagCode = value;
    this.setState({
      optionLoading: true,
      searchParams
    });
    financeAuditService.getExpCodeOption(value, status === 'prending_audit').then(res => {
      this.setState({
        optionLoading: false,
        expOption: res.data
      });
    }).catch(e => {
      this.setState({optionLoading: false});
      message.error(e.response.data.message);
    })
  };

  handleChangeTag = value => {
    const { searchParams } = this.state;
    searchParams.isRefBagCode = value === '1001';
    searchParams.expBagCode = null;
    this.setState({searchParams})
  };

  onFocus = () => {
    this.handleEnterInvoiceCode(this.state.searchParams.expBagCode);
  };

  onBlur = () => {
    const { expOption, searchParams } = this.state;
    if(!expOption.some(item => item.expenseReportBagCode === searchParams.expBagCode)){
      this.handleEnterInvoiceCode();
    }
  };

  handleDepartment = (value) => {
    this.setState({departmentOids: value});
  };

  changeAuditStatus = (value) => {
    this.setState({auditStatus: value});
    // console.log("value", value)
  }

  changeReceiveStatus = (value) => {
    this.setState({receiveStatus: Number(value)});
  }

  changeBilled = (value) => {
    this.setState({billed: Number(value)});
  }

  render() {
    const { data, loading, invoiceColumns ,borrowColumns, pagination, searchForm, nowType, status, searchParams, expOption, optionLoading, departmentOids } = this.state;
    let extraFields = [
      <div>
        <div style={{lineHeight: '28px'}}>
          {messages('financial-management.key145'/*成本中心*/)}
        </div>
        <CostCenterSearchForm title={messages('financial-management.key145'/*成本中心*/)}
                              value={searchParams.searchCostCenterCommands}
                              onChange={this.changeCostCenter}/>
      </div>,
      <div>
        <div className={'extra-title'}>{messages('financial-management.key448')/*部门*/}</div>
        <div>
          <DepartmentPicker placeholder={messages('common.please.select')}
                            type='department'
                            related
                            value={departmentOids}
                            onChange={this.handleDepartment}/>
        </div>
      </div>
    ];
    nowType === 'INVOICE' && (extraFields.push(<div>
      <div className={'extra-title'}>
        <Col span={6}>{messages('financial-management.key661')/*关联发票袋*/}</Col>
        <Col span={16} offset={2}>{messages('financial-management.key660')/*发票袋编号*/}</Col>
      </div>
      <div>
        <Col span={6}>
          <Select
            placeholder={messages('common.please.select')}
            onChange={this.handleChangeTag}
            value={typeof searchParams.isRefBagCode === 'boolean' ? (searchParams.isRefBagCode ? '1001' : '1002') : undefined}
            getPopupContainer={triggerNode => triggerNode.parentNode}
          >
            <Option key={'1001'}>{messages('financial-management.key316')/*是*/}</Option>
            <Option key={'1002'}>{messages('financial-management.key317')/*否*/}</Option>
          </Select>
        </Col>
        <Col span={16} offset={2}>
          <Select
            allowClear
            mode='combobox'
            value={searchParams.expBagCode || undefined}
            disabled={!searchParams.isRefBagCode}
            optionFilterProp="children"
            placeholder={messages('financial-management.key662')/*请输入编号*/}
            notFoundContent={optionLoading ? <Spin size="small"/> : messages('components.key405'/*无匹配结果*/)}
            onBlur={() => {this.onBlur()}}
            onFocus={() => this.onFocus()}
            onChange={(value) => this.handleEnterInvoiceCode(value)}
            showSearch
            getPopupContainer={triggerNode => triggerNode.parentNode}
          >
            {expOption.map(item => {
              return <Option key={item.expenseReportBagCode}>{item.expenseReportBagCode}</Option>
            })}
          </Select>
        </Col>
      </div>
    </div>));
    nowType === 'INVOICE' && (extraFields.push(<div>
      <div className={'extra-title'}>
        <Row span={6}>{messages('expense-11.key25'/*审核状态*/)}</Row>
      </div>
      <div>
        <Row>
          <Select placeholder="请选择" onChange={this.changeAuditStatus} defaultValue={localStorage.getItem('isBackFinance') === 'true' ? this.props.financeAuditParams && this.props.financeAuditParams.auditStatus : undefined}>
            <Option value="audit_review">{messages('financial-management.key1245'/*预审中*/)}</Option>
            <Option value="audit_review_passed">{messages('financial-management.key1246'/*复审中*/)}</Option>
          </Select>
        </Row>
      </div>
    </div>));
    nowType === 'INVOICE' && (extraFields.push(<div>
      <div className={'extra-title'}>
        <Row span={6}>{messages('financial-management.key1247'/*收件状态*/)}</Row>
      </div>
      <div>
        <Row>
          <Select placeholder="请选择" onChange={this.changeReceiveStatus} defaultValue={localStorage.getItem('isBackFinance') === 'true' ? this.props.financeAuditParams && this.props.financeAuditParams.receiveStatus : undefined}>
            <Option value={0}>{messages('financial-management.key1248'/*未收件*/)}</Option>
            <Option value={1}>{messages('financial-management.key1249'/*已收件*/)}</Option>
            <Option value={3}>{messages('financial-management.key1250'/*无需收件*/)}</Option>
          </Select>
        </Row>
      </div>
    </div>));
    nowType === 'INVOICE' && (extraFields.push(<div>
      <div className={'extra-title'}>
        <Row span={6}>{messages('basic-16.key72'/*开票状态*/)}</Row>
      </div>
      <div>
        <Row>
          <Select placeholder="请选择" onChange={this.changeBilled} defaultValue={localStorage.getItem('isBackFinance') === 'true' ? this.props.financeAuditParams && this.props.financeAuditParams.billed : undefined}>
            <Option value={1}>{messages('components.key1347'/*无需开票*/)}</Option>
            <Option value={2}>{messages('supplier-3.key43'/*未开票*/)}</Option>
            <Option value={3}>{messages('components.key218'/*开票通过*/)}</Option>
          </Select>
        </Row>
      </div>
    </div>));
    return (
      <div className="finance-audit">
        {
          this.checkFunctionProfiles(['finance.scan.disabled'], [[false, undefined]]) &&
          this.checkPageRole('EXPENSEAUDIT', 2) && false &&
          <Button type="primary"  data-control="test" icon="scan" onClick={this.handleClickSwitch} style={{ marginRight: 10 }}>{messages('financial-management.key205'/*APP扫码审核*/)}</Button>
        }
        {
          this.checkFunctionProfiles('document.review.enable', [true]) &&
          this.checkPageRole('EXPENSEAUDIT', 2) &&
          <Button type="primary" icon="qrcode" onClick={this.handleClickSwitchGun}>{messages('financial-management.key206'/*扫码枪审核*/)}</Button>
        }
        <Tabs type="card" onChange={this.onChangeTabs} activeKey={status} >
          {this.renderTabs()}
        </Tabs>
        <SearchArea onRef={this.onRef}
                    searchForm={searchForm}
                    wrappedComponentRef={inst => this.formRef = inst}
                    submitHandle={this.search}
                    extraFields={extraFields}
                    extraFieldsIndex={3}
                    clearHandle={this.clear}
                    isReturnLabel={true}
                    eventHandle={this.searchEventHandle}/>
        <div className="divider"/>
        <div className="table-header">
          <div className="table-header-title">{messages('common.total', {total: pagination.total})}</div>
          {/* 共total条数据 */}
        </div>
        <If value={nowType === 'INVOICE'}>
          <CustomTable allColumns={invoiceColumns}
                       localKey={"finance-audit-expense"}
                       tableOption={{
                         rowKey: record => record.expenseReportOID,
                         loading,
                         pagination,
                         hasFixed: true,
                         scroll: { x: 1200 },
                         columns: invoiceColumns,
                         expandedRowRender: dealListTag,
                         onChange: this.handleTableChange,
                         onRow: record => ({
                           onClick: () => this.handleRowClick(record)
                         }),
                         rowClassName: record => (record.printFree || record.noticeFlag ||  record.warningList  ) ? '' :'finance-audit-reject',
                         bordered: true,
                         dataSource: data
                       }}/>
        </If>
        <If value={nowType === 'BORROW'}>
          <CustomTable allColumns={borrowColumns}
                       localKey={"finance-audit-loan"}
                       tableOption={{
                         rowKey: record => record.loanBillOid,
                         loading,
                         pagination,
                         columns: borrowColumns,
                         hasFixed: true,
                         scroll: { x: 1200 },
                         expandedRowRender: dealListTag,
                         onChange: this.handleTableChange,
                         onRow: record => ({
                           onClick: () => this.handleRowClick(record)
                         }),
                         rowClassName: record => (record.printFree || record.noticeFlag ||  record.warningList  ) ? '' :'finance-audit-reject',
                         bordered: true,
                         dataSource: data
                       }}/>
        </If>
      </div>
    )
  }

}

FinanceAudit.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    companyConfiguration: state.login.companyConfiguration,
    profile: state.login.profile,
    company: state.login.company,
    user: state.login.user,
    financeAudit: state.cache.financeAudit,
    authToken: state.main.authToken,
    financeAuditParams: state.cache.financeAuditParams
  }
}

export default connect(mapStateToProps)(FinanceAudit);
